<?php

namespace App\Http\Controllers\Api;


use App\Jobs\Circle\UpdateCircleCountJob;
use App\Models\Posts\WxComment;
use App\Models\Posts\WxPost;
use App\Models\User\WxUserFollow;
use App\Models\User\WxUserOnline;
use App\Models\WxPlate;
use App\Models\User\WxUserVisit;
use App\Models\WxTenant;
use App\Wen\Utils\CircleUtils;
use App\Wen\Utils\Settings;
use App\Wen\Utils\UserUtils;
use App\Wen\Utils\Utils;
use App\Http\Controllers\Api\Repositories\WxCircleRepositores;
use App\Models\Circle\WxCircle;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Models\Posts\WxUserCircle;
use App\Models\User\WxUser;
use Illuminate\Support\Facades\DB;


class CircleController extends BaseController
{
    /**
     * 推荐
     * @return \Illuminate\Http\JsonResponse
     */
    public function recommendCircle()
    {
        return $this->success(WxCircleRepositores::recommendCircle());
    }

    /**
     * 热门
     * @return \Illuminate\Http\JsonResponse
     */
    public function hotCircle()
    {
        return $this->success(WxCircleRepositores::hotCircle());
    }

    /**
     * 最新
     * @return \Illuminate\Http\JsonResponse
     */
    public function newCircle()
    {
        return $this->success(WxCircleRepositores::newCircle());
    }

    /**
     * 获取全部
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request)
    {
        $page = $request->page;
        return $this->success(WxCircleRepositores::list($page));
    }

    /**
     * 获取圈子组合列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function circleAndPosts(Request $request)
    {
        $limit = $request->input('limit', 10);
        return $this->success(WxCircleRepositores::circleAndPost($limit));
    }

    /**
     * 用户关注圈子
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function followCircle(Request $request)
    {
        $uid = $request->uid;
        _limit_user('follow:circle', $uid, 20);
        $circle_id = $request->circle_id;

        $payment_duration = null;
        $circle = WxCircle::find($circle_id);
        if(_empty_($circle)){
            return $this->fail(200003);
        }
        $can_i_visit = CircleUtils::can_i_visit($circle, $uid);
        if($can_i_visit == 2){
            if($circle->is_follow_pay == 1){
                if($circle->follow_pay_credit == 1){
                    // 余额支付
                    return (new OrderController())->balance_pay($request);
                }else{
                    // 金币支付
                    DB::beginTransaction();
                    try {
                        // todo:
                        // 金币直接结清
                        $platform_division = _between_(Settings::get('app_circle_follow_pay_division', 0), 0, 100);
                        $platform_reward = round($platform_division * $circle->follow_pay_num / 100, 2);
                        $circle_user_reward = round($circle->follow_pay_num - $platform_reward, 2);

                        $pay_res2 = UserUtils::update_user_coins($uid, 20, -$circle->follow_pay_num, '付费加入了「'.$circle->circle_name.'」'.env('circle_call', '圈子').'，-'.$circle->follow_pay_num.Settings::get('app_coin_name', '硬币'));
                        if($pay_res2){
                            $r = WxCircleRepositores::userFollowCircle($uid, $circle->id, Carbon::now()->addDays((int)$circle->follow_pay_duration)->toDateTimeString());
                            if($r){
                                if($circle_user_reward >= 0.01){
                                    $pay_res_ = UserUtils::update_user_coins($circle->user_id, 21, $circle_user_reward, '有新的用户(id: '.$uid.')加入您的付费'.env('circle_call', '圈子').'，扣掉平台分成'.$platform_division.'%，您'.Settings::get('app_coin_name', '硬币').'+'.$circle_user_reward.'。');
                                }
                            }else{
                                DB::rollBack();
                                return $this->fail(200011, [], Settings::get('app_coin_name', '硬币').'不足');
                            }
                        }else{
                            DB::rollBack();
                            return $this->fail(200011, [], Settings::get('app_coin_name', '硬币').'不足');
                        }
                        DB::commit();
                        return $this->success(WxCircleRepositores::userFollowCircle($uid, $circle_id));
                    } catch (\Exception $e) {
                        DB::rollBack();
                        _logger_(__file__, __line__, $e->getMessage());
                        return $this->fail(200011);
                    }
                }
            }else{
                _logger_(__file__, __line__, '逻辑出现问题，为什么会走到这里？');
            }
        }else{
            return $this->success(WxCircleRepositores::userFollowCircle($uid, $circle_id));
        }
    }

    /**
     * 用户关注圈子文章组合列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function userFollowCircleList(Request $request)
    {
        $uid = $request->uid;
        $limit = $request->input('limit', 10);
        return $this->success(WxCircleRepositores::userFollowCircleList($uid, $limit));
    }

    /**
     * 获取圈子详细
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCircleInfoById(Request $request)
    {
        $circle_id = $request->circle_id;
        $uid = $request->uid;
        $is_tenant = _empty_default_($request->isTenant, false);
        if(_empty_($is_tenant)){
            $is_tenant = false;
        }else{
            $is_tenant = true;
        }
        if(_empty_($circle_id)){
            return $this->fail(200001);
        }
        $data = WxCircleRepositores::CircleInfo($circle_id);
        if(_empty_($data)){
            return $this->fail(200003);
        }
        $data->is_follow_circle = WxCircleRepositores::isFollowCircle($uid, $circle_id);
        $data->plate = WxPlate::where('id', $data->plate_id)->first(['id', 'plate_name', 'plate_introduce']);
        if($uid > 0){
            update_user_visit($uid, 2, $circle_id);
        }
        $data->circle_tags = CircleUtils::circle_tags($data->id);
        $data->circle_notice = CircleUtils::sticky_notice_list($data->id);
        $data->circle_sqare = CircleUtils::circle_square_list($data);
        $data->pay_content_count = WxPost::where('circle_id', $circle_id)->where('pay_content_id', '>', 0)->where('is_examine', 1)
            ->where('posts_state', 0)->count();
        if($data->pay_content_count != $data->count_pay_content){
            UpdateCircleCountJob::dispatch($circle_id);
        }
        $data->comment_count = WxComment::where('posts_circle_id', $circle_id)->where('comment_state', 1)->count();
        if($data->comment_count != $data->count_comment){
            UpdateCircleCountJob::dispatch($circle_id);
        }
        $data->can_i_visit = CircleUtils::can_i_visit($data, $uid);
        if($data->can_i_visit == 2){
            if($data->follow_pay_num > 0 && $data->follow_pay_duration != 0){
                $data->follow_pay_day_tip = '低至 '.round($data->follow_pay_num / $data->follow_pay_duration, 2).($data->follow_pay_credit == 1 ? '余额' : Settings::get('app_coin_name', '硬币')).'/天';
            }
        }else if($data->can_i_visit == 1){
            $data->follow_payment_duration = WxUserCircle::where('user_id', $uid)->where('circle_id', $data->id)->value('payment_duration');
        }
        if($data->tenant_show != -1){
            $data->tenant_show_obj = WxTenant::find($data->tenant_show);
        }
        $data->format_time = format_datetime($data->created_at); // 发帖时间
        if($uid > 0){
            $data->continuous_to_circle = _empty_default_(get_user_meta($uid, 'continuous_to_circle:'.$data->id, 'j'), [
                'days' => 1,
                'updated_at' => ''
            ]);
        }else{
            $data->continuous_to_circle = null;
        }
        return $this->success($data);
    }

    public function getCircleUserList(Request $request)
    {
        $uid = $request->uid;
        $circle_id = $request->circle_id;
        if(_empty_($circle_id)){
            return $this->fail(200001);
        }
        $circle_user_id = WxCircle::where('id', $circle_id)->value('user_id');
        if(_empty_($circle_user_id)){
            $circle_user_id = 0;
        }
        $circleUserList = WxUserCircle::where([['circle_id','=', $circle_id],['user_id', '<>', $circle_user_id]])->orderBy('id', 'desc')->limit(9)->get();
        $user_id_arr = [];
        if($circle_user_id){
            $user_id_arr[] = $circle_user_id;
        }
        foreach ($circleUserList as $k => $v) {
            $user_id_arr[] = $v['user_id'];
        }

        $data = WxUser::whereIn('id', $user_id_arr)->orderBy(DB::raw('FIND_IN_SET(id, "' . implode(",", $user_id_arr) . '"' . ")"))
            ->get(['user_avatar', 'user_name', 'id', 'user_introduce']);
        if($data){
            $data->map(function ($v) use ($uid){
                $online_item = WxUserOnline::where('user_id', $v->id)->first(['online', 'device']);
                if($online_item){
                    $v->online_time = format_datetime($online_item->online);
                    $v->device = $online_item->device;
                }else{
                    $v->online_time = '暂时未知';
                    $v->device = '';
                }
                $v->is_follow_user = (new WxUserFollow())->isFollowUser($uid, $v->id);
                return $v;
            });
        }

        return $this->success($data);
    }

    public function poster(Request $request){
        $circleId = $request->id;
        $uid = $request->uid;
        if(_empty_($circleId)){
            return $this->fail(200001);
        }

        $circle = WxCircle::find($circleId);
        if(_empty_($circle)){
            return $this->fail(200003);
        }
        $mini_code = Utils::getMiniCode('pages/circle/list', 'id='.$circle->id, $uid);

        $h5 = Settings::get('app_h5_home', '');
        $url = env('APP_URL').'/circle/' . $circle->id;
        if(!_empty_($h5)){
            $url = $h5 . '#/pages/circle/list?id='.$circle->id;
        }

        if($mini_code){
            $data = [
                'url' => $url,
                'name' => $circle->circle_name,
                'desc' => $circle->circle_introduce,
                'avatar' => $circle->head_portrait,
                'bg' => $circle->background_maps,
                'code' => $mini_code
            ];
            return $this->success($data);
        }else{
            return $this->fail(300001);
        }
    }


    public function nearlyAndfollow(Request $request){
        $uid = $request->uid;

        $result = [
            'nearly' => [],
            'follow' => []
        ];

        global $__MINI_GLOBAL_TENANT_ID__;

        if($uid > 0){
            $object_ids = WxUserVisit::where([['user_id','=', $uid],['type', '=', 2]])->orderBy('updated_at', 'desc')->limit(20)->pluck('object_id');
            if($object_ids){

                $query = WxCircle::whereIn('id', $object_ids)->orderBy(DB::raw('FIND_IN_SET(id, "' . implode(",", $object_ids->toArray()) . '"' . ")"));
                $query = $query->where('tenant_id', $__MINI_GLOBAL_TENANT_ID__);

                $nearly_circles = $query->get(['id','circle_name', 'head_portrait'])->map(function ($v){
                    $v->name = $v->circle_name;
                    $v->img = $v->head_portrait;
                    $v->type = 2;
                    $v->target = $v->id;
                    return $v;
                });
                $result['nearly'] = $nearly_circles;
            }


            $follow_ids = WxUserCircle::where([['user_id', '=', $uid], ['user_circle_state', '=', 0]])->orderBy('updated_at', 'desc')->pluck('circle_id');
            if($follow_ids){
                $follow_query = WxCircle::whereIn('id', $follow_ids);
                $follow_query = $follow_query->where('tenant_id', $__MINI_GLOBAL_TENANT_ID__);

                $follow_circle = $follow_query->orderBy(DB::raw('FIND_IN_SET(id, "' . implode(",", $follow_ids->toArray()) . '"' . ")"))->get()->map(function ($v) use ($uid){
                    $v->is_dot = !UserUtils::is_user_readed_circle($uid, $v->id);
                    return $v;
                });
                if($follow_circle){
                    $follow_circle->append(['circle_user', 'circle_follow_count', 'circle_posts_count']);
                }
                $result['follow'] = $follow_circle;
            }

        }

        return $this->success($result);
    }

}
